package me.bincker.formwork.web.modules.system.controller

import me.bincker.formwork.web.core.annotation.Permission
import me.bincker.formwork.web.core.exception.NotFoundException
import me.bincker.formwork.web.core.validated.ValidAdd
import me.bincker.formwork.web.core.validated.ValidPut
import me.bincker.formwork.web.modules.system.entity.Menu
import me.bincker.formwork.web.modules.system.service.IMenuService
import org.springframework.data.domain.Pageable
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("menus")
class MenuController(
        private val menuService: IMenuService
) {
    @GetMapping
    @Permission("菜单列表", "menu.page")
    fun getPage(pageable: Pageable) = menuService.findAll(pageable)

    @GetMapping("{id}")
    @Permission("菜单详情", "menu.get")
    fun get(@PathVariable id: String): Menu {
        return menuService.findById(id) ?: throw NotFoundException()
    }

    @GetMapping("{id}/children")
    @Permission("获取子菜单列表", "menu.children")
    fun getChildren(@PathVariable id: String) =
            menuService.findById(id)?.children ?: throw NotFoundException()

    @PostMapping
    @Permission("添加菜单", "menu.add")
    fun add(@Validated(ValidAdd::class) menu: Menu): Menu{
        return menuService.save(menu)
    }

    @PutMapping
    @Permission("修改菜单", "menu.edit")
    fun put(@Validated(ValidPut::class) menu: Menu): Menu{
        return menuService.save(menu)
    }

    @PatchMapping
    @Permission("修改菜单", "menu.edit")
    fun edit(@Validated menu: Menu): Menu{
        val target = menuService.getOne(menu.id)
        target.name = menu.name ?: target.name
        target.url = menu.url ?: target.url
        target.icon = menu.icon ?: target.icon
        target.hidden = menu.hidden ?: target.hidden
        target.parent = menu.parent ?: target.parent
        target.type = menu.type ?: target.type
        target.orderNumber = menu.orderNumber ?: target.orderNumber
        return menuService.save(target)
    }
}